package com.sh.utils;

import com.sh.mapper.BoatMapper;
import com.sh.pojo.Boat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class UdpServer implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(UdpServer.class);
    @Autowired
    private BoatMapper boatMapper;
    private static final int PORT = 11111;
    private static int count = 0;
    private DatagramSocket socket;
    private final BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>();
    private List<String> Message;

    public UdpServer(List<String> message) {
        Message = message;
    }

    @Override
    public void run(String... args) throws Exception {
        socket = new DatagramSocket(PORT);
        new Thread(() -> {
            byte[] buffer = new byte[65535];
            while (!socket.isClosed()) {
                try {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    socket.receive(packet);

                    String message = new String(packet.getData(), 0, packet.getLength(), "GBK");
                    log.info("接受住了: {}", message);
                    messageQueue.put(message); // 存入消息队列
                    solve(message, packet);
//                    count += 1;
//                    if (count == 10) {
//                        // 数据库操作
//                        Boat boat = new Boat();
//                        boat.setIp(packet.getAddress().getHostAddress());
//                        boat.setPort(packet.getPort());
//                        String ans = parseMessage(message);
//                        boat.setMessage(ans);
//                        boatMapper.update(boat);
//                        count = 0;
//                    }

                } catch (Exception e) {
                    if (!socket.isClosed()) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public String getLatestMessage() {
        try {
            return messageQueue.poll(1, TimeUnit.SECONDS); // 非阻塞获取
        } catch (InterruptedException e) {
            return null;
        }
    }
    public  String getMesage(){
        Boat boat = boatMapper.getBoat();
        return boat.getMessage();
    }

    @PreDestroy
    public void destroy() {
        if (socket != null) {
            socket.close();
        }
    }

    public void solve(String message, DatagramPacket packet) {
        // 正则表达式：匹配被双引号包围的任意字符（非贪婪模式）
        Pattern pattern = Pattern.compile("\"([^\"]*)\"");
        Matcher matcher = pattern.matcher(message);
        if (matcher.find()) {
            if (Message.size()<10)Message.add(matcher.group(1));
            if(Message.size()==10){
                count++;
                if (count == 20) {
                    Boat boat = new Boat();
                       boat.setIp(packet.getAddress().getHostAddress());
                       boat.setPort(packet.getPort());
                       boat.setMessage(Message.toString());
                       boatMapper.update(boat);
                       count = 0;
                }
            }
            System.out.println(matcher.group(1)); // 返回第一个捕获组（即双引号内的内容）
            System.out.println(Message);
        }

    }


}